package com.zhouxiao.multithreading.ThreadLocal;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class MyThreadLocal<T> {

    static AtomicInteger atomicInteger = new AtomicInteger();

    Integer threadLocalHash = atomicInteger.addAndGet(0x61c88647);

    static Map<Thread, HashMap<Integer, Object>> threadHashMapMap = new HashMap<>();

    synchronized static HashMap<Integer, Object> getMap() {
        Thread thread = Thread.currentThread();
        if (!threadHashMapMap.containsKey(thread)) {
            threadHashMapMap.put(thread, new HashMap<>());
        }
        return threadHashMapMap.get(thread);
    }


    protected T initialValue() {
        return null;
    }

    public T get() {
        HashMap<Integer, Object> map = getMap();
        if (!map.containsKey(this.threadLocalHash)) {
            map.put(this.threadLocalHash, initialValue());
        }
        return (T) map.get(this.threadLocalHash);
    }

    public void set(T v) {
        HashMap<Integer, Object> map = getMap();
        map.put(threadLocalHash, v);
    }
}
